package com.example.zcl.system.minio;

/**
 * @desc: --
 * @author: Bing
 * @date: 2025-06-27 16:12
 */

import cn.hutool.core.date.DateUtil;
import com.example.zcl.system.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

@RestController
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        String url = "";
        try {
            // 获取原始文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(DateUtil.date());
            //String fileName = datePath + "/" + IdUtil.simpleUUID() + suffix;
            String fileName = datePath + "/" + originalFilename;
            minioUtil.uploadFile(fileName, file);
            url = "http://192.168.5.6:9000/" + "beibo" + "/" + fileName;
            return Result.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/download")
    public void download(@RequestParam String fileName, HttpServletResponse response) {
        try (InputStream is = minioUtil.downloadFile(fileName);
             OutputStream os = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
